package com.syqc.monitor.ui.newaddcar

import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.luck.picture.lib.entity.LocalMedia
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.KeyValue
import com.syqc.entity.TmnManager
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import com.syqc.utils.NetDataUtil
import com.syqc.utils.ToolsUtil
import okhttp3.MultipartBody
import kotlin.concurrent.thread

/**
 *@Author Jasper
 *@Time   2021/1/8
 *@Desc   todo
 */
class AddNewCarViewModel : AutoDisposeViewModel() {
    //车牌
    var carPlate = ""
    var carName = ""
    var colorId = ""
    var teamId = ""
    var videoPass = ""
    var owner = ""
    var ownerPhone = ""
    var des = ""

    //表示定义
    var keyType = ""


    var tmnId = ""
    var tmnNum = ""
    var simNum = ""
    var tmnKey = ""
    var colorIndex = 0

    //录入终端
    var isInputTmn = false

    //选择终端
    var isChooseTmn = false

    val colorList = mutableListOf<KeyValue>()
    val colorLive = MutableLiveData<KeyValue>()
    var videoChannel: String? = null

    init {
        initColors()
    }

    /**
     * 车辆颜色
     *
     */
    private fun initColors() {
        if (NetDataUtil.colors != null) {
            NetDataUtil.colors?.forEach { colorList.add(KeyValue(it.id, it.name)) }
        }
        colorId = colorList[0].key
        colorLive.postValue(KeyValue("color", colorList[0].value))
    }

    /**
     * 车辆信息参数
     *
     * @return
     */
    private fun isCarParamsOk(): Boolean {
        if (carPlate.isEmpty()) {
            toast(R.string.hint_login_car)
            return true
        }
        if (teamId.isEmpty()) {
            toast(R.string.hint_toast_choose_team)
            return true
        }
        return false
    }

    /**
     * 终端信息参数
     *
     * @return
     */
    private fun isTmnParamsOk(): Boolean {
        if (keyType == "1" && simNum.isEmpty()) {
            toast(R.string.hint_toast_sim)
            return true
        }
        if (keyType == "2" && tmnNum.isEmpty()) {
            toast(R.string.hint_toast_tmn)
            return true
        }

        if (keyType == "3" && tmnKey.isEmpty()) {
            toast(R.string.hint_toast_sign_define)
            return true
        }
        return false
    }

    private val maxCarNum = 8
    var nowCarNum = maxCarNum
    private var carIndex = 0
    private val photoCars = mutableListOf("", "", "", "", "", "", "", "")
    val photoLive = MutableLiveData<MutableList<String>>()

    //处理车辆照片
    fun handlePhoto(data: ArrayList<LocalMedia>?) {
        if (data.isNullOrEmpty()) {
            photoLive.postValue(photoCars)
            return
        }
        data.forEach {
            photoCars[carIndex] = it.path
            carIndex++
        }
        nowCarNum = maxCarNum - carIndex
        photoLive.postValue(photoCars)
    }

    //移除车辆照片
    fun removePhoto(index: Int) {
        photoCars.removeAt(index)
        carIndex--
        photoCars.add("")
        nowCarNum = maxCarNum - carIndex
        photoLive.postValue(photoCars)
    }

    private val maxTmnNum = 8
    var nowTmnNum = maxTmnNum
    private var tmnIndex = 0
    private val photoTmns = mutableListOf("", "", "", "", "", "", "", "")
    val photoTmnLive = MutableLiveData<MutableList<String>>()

    //处理终端照片
    fun handleTmnPhoto(data: ArrayList<LocalMedia>?) {
        if (data.isNullOrEmpty()) {
            photoTmnLive.postValue(photoTmns)
            return
        }
        data.forEach {
            photoTmns[tmnIndex] = it.path
            tmnIndex++
        }
        nowTmnNum = maxTmnNum - tmnIndex
        photoTmnLive.postValue(photoTmns)
    }

    private var keys = ArrayList<String>()

    //终端照片处理
    fun handleTmnUrlPhoto(pics: Map<String, String>?) {
        tmnIndex = 0
        pics?.forEach {
            photoTmns[tmnIndex] = it.value
            keys.add(it.key)
            tmnIndex++
        }
        nowTmnNum = maxTmnNum - tmnIndex
        photoTmnLive.postValue(photoTmns)
    }

    //移除终端照片
    fun removeTmnPhoto(index: Int) {
        photoTmns.removeAt(index)
        tmnIndex--
        photoTmns.add("")
        nowTmnNum = maxTmnNum - tmnIndex
        photoTmnLive.postValue(photoTmns)
    }

    //重置信息
    fun resetInfo() {
        tmnId = ""
        keyType = ""
        tmnIndex = 0
        nowTmnNum = 8
        photoTmns.clear()
        (0..<maxTmnNum).forEach { _ ->
            photoTmns.add("")
        }
        photoTmnLive.postValue(photoTmns)
    }


    fun addNewCar() {
        if (isCarParamsOk()) return
        if (isChooseTmn) {
            if (isRepeat2()) return
            toastLoading(true)
            thread {
                addNewCar2()
            }
            return
        }
        if (isInputTmn) {
            if (isTmnParamsOk()) return
        }
        if (isRepeat()) return
        toastLoading(true)
        thread {
            parts.clear()
            getCarParts()
            getTmnParts()
            if (carName.isEmpty()) {
                carName = carPlate
            }
            ServiceHelper.getRepository().addNewCar(
                carPlate, colorId, simNum,
                tmnNum, tmnKey, teamId, keyType,
                videoPass, owner, ownerPhone, des, videoChannel, carName, parts
            ).autoDispose(this).subscribe({
                oldCarTmnInfo = newCarTmnInfo
                toastLoading(false)
                toast(R.string.toast_add_success)
            }, error)
        }

    }


    private fun addNewCar2() {
        parts.clear()
        getCarParts()
        if (carName.isEmpty()) {
            carName = carPlate
        }
        ServiceHelper.getRepository().addNewCar2(
            carPlate,
            colorId,
            teamId,
            videoPass,
            owner,
            ownerPhone,
            des,
            tmnId,
            videoChannel,
            carName,
            parts
        ).autoDispose(this).subscribe({
            oldCarInfo = newCarInfo
            toastLoading(false)
            toast(R.string.toast_add_success)
        }, error)
    }

    private val parts = ArrayList<MultipartBody.Part?>()
    private fun getTmnParts() {
        photoTmns.forEachIndexed { index, s ->
            if (s.isNotEmpty()) parts.add(ToolsUtil.getPartByPath("files", "tmn_pic_$index", s))
        }
    }

    private fun getCarParts() {
        photoCars.forEachIndexed { index, s ->
            if (s.isNotEmpty()) parts.add(ToolsUtil.getPartByPath("files", "car_pic_$index", s))
        }
    }

    private var oldCarTmnInfo: String = ""
    private var newCarTmnInfo: String = ""

    //是否重复
    private fun isRepeat(): Boolean {
        val carPhotos = GsonUtil.toJson(photoCars)
        val tmnPhotos = GsonUtil.toJson(photoTmns)
        newCarTmnInfo =
            "$carPlate$carName$colorId$simNum$tmnNum$tmnKey$teamId$videoPass$owner$ownerPhone$des$keyType$videoChannel$carPhotos$tmnPhotos"
        if (oldCarTmnInfo == newCarTmnInfo) {
            toast(R.string.toast_repeat_same_data)
            return true
        }
        return false
    }

    private var oldCarInfo: String = ""
    private var newCarInfo: String = ""

    //是否重复
    private fun isRepeat2(): Boolean {
        val newPhotos = GsonUtil.toJson(photoCars)
        newCarInfo =
            "$carPlate$carName$colorId$teamId$videoPass$owner$ownerPhone$des$tmnId$videoChannel$newPhotos"

        if (oldCarInfo == newCarInfo) {
            toast(R.string.toast_repeat_same_data)
            return true
        }
        return false
    }

    val tmnsLive = MutableLiveData<ArrayList<TmnManager>>()

    //获取终端
    fun getTmnByTeam() {
        toastLoading(true)
        ServiceHelper.getRepository().getTmnByTeam(teamId).autoDispose(this).subscribe({
            toastLoading(false)
            if (isHasListData(it)) return@subscribe
            tmnsLive.postValue(it)
        }, error)
    }
}
